#!/bin/bash

IMAGES=(
'10.0.16.125:5080/general/ubuntu:16 ubuntu16/'
'10.0.16.125:5080/general/ubuntu-mongodb:16-3.4 ubuntu16-mongodb3.4/'
'10.0.16.125:5080/general/ubuntu-mysql:16 ubuntu16-mysql/'
'10.0.16.125:5080/general/ubuntu-nginx:16 ubuntu16-nginx/'
'10.0.16.125:5080/general/ubuntu-rabbitmq:16 ubuntu16-rabbitmq/'
'10.0.16.125:5080/general/ubuntu-redis:16 ubuntu16-redis/'
'10.0.16.125:5080/general/ubuntu-tomcat:16-7 ubuntu16-tomcat7/'
'10.0.16.125:5080/general/centos:7 centos7/'
'10.0.16.125:5080/general/centos-mariadb:7-10.1 centos7-mariadb10.1/'
'10.0.16.125:5080/general/centos-tomcat:7 centos7-tomcat/'
'10.0.16.125:5080/general/centos-nginx:7 centos7-nginx/'
'10.0.16.125:5080/other/nginx-fileindex:centos7 nginx-fileindex/'
'10.0.16.125:5080/other/centos-gogs:7 centos7-gogs/'
)

function Quit {
    [ -n "$1" ] && echo -e "\n\033[31;1m ERROR: $1!\033[0m"
    exit 1
}

function ShowImage {
    local i
    for i in ${!IMAGES[@]}; do
        echo -e "\033[32;1m$i:\033[0m ${IMAGES[$i]}"
    done
}

function RemoveImage {
    local yn
    docker images --format='{{.Repository}}:{{.Tag}}' \
        | grep "^$1$"
    if [ 0 -eq $? ]; then
        echo -e "\033[32;1mAlready exists Image\033[0m: $1"
        while :; do
            read -n 1 -p "rebuild it? (Y/n): " yn
            case "$yn" in
            ''|y|Y)
                echo -e "\n\033[33;1mRemoving image\033[0m: $1 ..."
                docker rmi $1 || Quit "remove image $1 failed"
                return 0
                ;;
            n|N)
                echo
                return 1
                ;;
            *)
                echo -e '\n\033[33;1mInput error!\033[0m'
                ;;
            esac
        done
    fi
}

function PushImage {
    local yn
    while :; do
        read -n 1 -p 'Push this image? (Y/n): ' yn
        case "$yn" in
        ''|y|Y)
            echo -e "\n\033[33;1mPushing image\033[0m: $1 ..."
            docker push $1 || Quit
            echo -e "\033[32;1mPush image:$imageRepo successfully.\033[0m"
            break
            ;;
        n|N)
            echo
            break
            ;;
        *)
            echo -e "\n\033[33;1mInput error!\033[0m"
            ;;
        esac
    done
}

# start
ShowImage
read -p 'Select one number to build image: ' num
if [[ "$num" =~ ^[0-9]+$ ]]; then
    [ -z "${IMAGES[$num]}" ] && Quit "not found image after: $num"
    imageRepo="$(echo "${IMAGES[$num]}"|awk '{print $1}')"
    RemoveImage "$imageRepo"
    if [ 0 -eq $? ]; then
        echo -e "\n\033[33;1mBuilding image\033[0m: $imageRepo ..."
        docker build -t ${IMAGES[$num]} || Quit
        echo -e "\033[32;1mBuild image:$imageRepo successfully.\033[0m"
    fi
    PushImage "$imageRepo"
else
    Quit "invalid number: $num"
fi

